package experiment1.sort;

public class MergeSort extends Sort {
    public MergeSort(int[] arr) {
        super(arr);
    }

    void merge(int left, int mid, int right) {
        int i = left, j = mid + 1;
        int k = 0;
        int[] temp = new int[right - left + 1];
        while ((i <= mid) && (j <= right)) {
            if (arr[i] <= arr[j]) {
                temp[k++] = arr[i++];
            } else {
                temp[k++] = arr[j++];
            }
        }

        while (j <= right) {
            temp[k++] = arr[j++];
        }

        while (i <= mid) {
            temp[k++] = arr[i++];
        }

        while (k > 0) {
            arr[--j] = temp[--k];
        }

    }

    @Override
    public void sort(int left, int right) {
        if (left < right) {
            int mid = left + (right - left) / 2;
            sort(left, mid);
            sort(mid + 1, right);
            merge(left, mid, right);
        }
    }
}
